package com.cht.commonUtil.infra;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.structure.S2;
import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class QueryEnv4Select extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( SP.UIcodeSet );
		
		String subsysId = request.getParameter("subsysId");
		String sql = "SELECT envId,envName FROM env WHERE subsysId=?";
		List<S2> envs = new ArrayList<S2>();
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = Widgets.getConn();
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			rs = ps.executeQuery();
			while ( rs.next() ) {
				S2 env = new S2();
				env.setS1( rs.getString("envId") );
				env.setS2( rs.getString("envName") );
				envs.add(env);
			}
		} catch(Exception e) {
			Widgets.errLog(e);
		} finally {
			try {
				if ( rs !=null ) { rs.close(); }
				if ( ps !=null ) { ps.close(); }
				if ( conn !=null ) { conn.close(); }
			} catch (Exception e) { e.printStackTrace(); }
		}
		
		response.getWriter().write( new Gson().toJson(envs) );
	}
}
